// app.js
import {getLoginCode,codeToToken,checkToken,checkSession} from "./service/api_login"
import {TOKEN_KEY} from "./constants/token-const"
App({
  globalData:{
    screenWidth:0,
    screenHeight:0,
    statusBarHeight:0,
    navBarHeight:44,
    deviceRadio:0
  },
  //启动时,监听小程序初始化
  onLaunch:function(){
    // 1.设备信息获取
    const info =wx.getSystemInfoSync()
    this.globalData.screenHeight=info.screenHeight
    this.globalData.screenWidth=info.screenWidth
    this.globalData.statusBarHeight=info.statusBarHeight
    const deviceRadio=info.screenHeight/info.screenWidth
    this.globalData.deviceRadio=deviceRadio
    // 2.让用户默认进行登录
    this.handleLogin()
   
  },
  handleLogin:async function(){
    const token=wx.getStorageSync(TOKEN_KEY)
    //token有没有过期 
    const cheeckResult=await checkToken()
    //console.log(cheeckResult.data);
    //判断session有没有过期
    const isSessionExpire=await checkSession()
    //errorCode:1001 =>没有提供token
    //errorCode:1002 =>提供错误token
    //errorCode:1003 =>提供token过期了
    if (!token ||cheeckResult.data.errorCode || !isSessionExpire) {
       this.loginAction()
    } 
  },
  loginAction:async function(){
    // 1.获取临时登录凭证code
    const code=await getLoginCode
    // 2.将code传给服务器
    const result = await codeToToken(code)
    const token=result.data.token
    wx.setStorageSync(TOKEN_KEY, token)
  }
})
